<template>
  <el-card class="box-card el-card-flex">
    <div slot="header" class="clearfix">
      <span>
        <i class="el-icon-connection"></i>
        用户组管理
      </span>
    </div>
    <!-- 表单 -->
    <div class="text item">
      <el-form :inline="true" :model="formSearch" class="demo-form-inline" @submit.native.prevent>
        <el-form-item label="">
          <el-input clearable v-model="formSearch.expression" placeholder="请输入用户组编码/名称" style="width:240px;" @keyup.enter.native="userGroupList" @clear="userGroupList">
            <el-button slot="append" icon="el-icon-search" @click="userGroupList"></el-button>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchDialog">
            高级查询
            <i class="el-icon-magic-stick"></i>
          </el-button>
        </el-form-item>
        <el-form-item style="float:right">
          <el-button type="primary" plain @click="addUserGroupDialog">
            新增
            <i class="el-icon-plus"></i>
          </el-button>
          <el-button type="danger" plain @click="userGroupDelRows" v-show="groupDelete">
            批量删除
            <i class="el-icon-delete"></i>
          </el-button>
        </el-form-item>
      </el-form>
      <!-- tabel表格 -->
      <div class="el-flex el-box-column">
        <el-table ref="groupTable" height="100%" style="width: 100%" border stripe :data="userGroupDatas" @selection-change="checkedRow">
          <el-table-column min-width="100px" sortable show-overflow-tooltip prop="userGroupCode" label="用户组编码"></el-table-column>
          <el-table-column min-width="100px" sortable show-overflow-tooltip prop="userGroupName" label="用户组名称"></el-table-column>
          <el-table-column min-width="100px" sortable show-overflow-tooltip prop="domainName" label="系统名称"></el-table-column>
					<el-table-column min-width="100px" sortable show-overflow-tooltip prop="createdByName" label="创建人" align="center"></el-table-column>
          <el-table-column min-width="100px" sortable show-overflow-tooltip prop="creationDate" label="创建时间" align="center"></el-table-column>
          <el-table-column width="110" sortable show-overflow-tooltip prop="groupStatus" label="用户组状态" align="center">
            <template slot-scope="scope">
							<el-switch v-model="scope.row.groupStatus" @change="userGroupStatusclick(scope.$index, scope.row)"></el-switch>
						</template>
					</el-table-column>
          <el-table-column width="150" show-overflow-tooltip label="操作" align="center" fixed="right">
            <template slot-scope="scope">
              <el-button class="td-btn-icon" type="text" title="修改用户组" @click="userGroupEditDialog(scope.row)"><i class="el-icon-edit"></i></el-button>
              <el-button @click="giveFuncEvt(scope.row)" class="td-btn-icon" type="text" title="数据授权"><i class="el-icon-medal"></i></el-button>
              <el-button class="td-btn-icon" type="text" title="删除用户组" @click="userGroupDelRow(scope.$index, scope.row)"><i class="el-icon-delete"></i></el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 分页 -->
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        :page-size="pageSize"
        :current-page="currentPage"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      ></el-pagination>
    </div>
    <!-- 高级查询抽屉式弹框 -->
    <el-drawer
      title="高级查询"
      :before-close="searchDialogCloseEvt"
      :visible.sync="searchDialogVisible"
      direction="rtl"
      custom-class="demo-drawer"
      ref="drawer"
      :wrapperClosable="true"
      :close-on-press-escape="false"
      >
      <div class="demo-drawer__content el-box-column" style="height: 100%; margin-left: 18px;">
        <el-form :model="userGroupSearchForm" ref="userGroupSearchForm" label-width="100px" class="el-flex">
          <el-form-item label="用户组编码:" prop="groupCode">
            <el-col :span="15">
              <el-input placeholder="请输入用户组编码" v-model="userGroupSearchForm.groupCode"></el-input>
            </el-col>
          </el-form-item>
          <el-form-item label="用户组名称:" prop="groupName">
            <el-col :span="12">
              <el-input placeholder="请输入用户组名称" v-model="userGroupSearchForm.groupName"></el-input>
            </el-col>
          </el-form-item>
          <el-form-item label="系统名称:" prop="domainName">
            <el-col :span="12">
              <el-input placeholder="请输入系统名称" v-model="userGroupSearchForm.domainName"></el-input>
            </el-col>
          </el-form-item>
          <el-form-item label="用户组状态:" prop="groupStatus">
            <el-radio-group v-model="userGroupSearchForm.groupStatus">
              <el-radio border label="">全部</el-radio>
              <el-radio border label="true">启用</el-radio>
              <el-radio border label="false">禁用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
        <div class="demo-drawer__footer" style="text-align: right; margin-bottom: 10px; padding-right:10px;">
          <el-button type="primary" @click="userGroupList">
            确定
            <i class="el-icon-document-checked el-icon--right"></i>
          </el-button>
          <el-button @click="userGroupReset">
            重置
            <i class="el-icon-refresh-left"></i>
          </el-button>
        </div>
      </div>
    </el-drawer>
    <!-- 用户组信息弹框 -->
    <el-dialog :title="title" :visible.sync="userGroupDialogVisible" :close-on-click-modal="false" :close-on-press-escape="false"
      :before-close="userGroupDialogCloseEvt">
      <el-form :model="userGroupForm" ref="userGroupForm" label-width="100px">
        <el-form-item
				  label="用户组编码:"
					prop="userGroupCode"
					:rules="[
						{
							required: true,
							message: '用户组编码不能为空'
						}
					]">
          <el-col :span="9">
            <el-input placeholder="请输入用户组编码" v-model="userGroupForm.userGroupCode" :readonly="readonly"></el-input>
          </el-col>
        </el-form-item>
        <el-form-item
				  label="用户组名称:"
					prop="userGroupName"
					:rules="[
						{
							required: true,
							message: '用户组名称不能为空'
						}
					]">
          <el-col :span="12">
            <el-input placeholder="请输入用户组名称" v-model="userGroupForm.userGroupName"></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="所属系统:"
          prop="domainId"
          :rules="[
						{
							required: true,
							message: '所属系统不能为空'
						}
					]"
        >
          <el-select v-model="userGroupForm.domainId" placeholder="请选择所属系统">
						<el-option
							v-for="item in this.optionDatas"
							:key="item.domainId"
							:label="item.domainName"
							:value="item.domainId">
						</el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="用户组状态:" prop="groupStatus">
          <el-switch v-model="userGroupForm.groupStatus"></el-switch>
        </el-form-item>
      </el-form>
      <el-row style="text-align:right">
				<el-button type="primary" plain @click="distributionGroup">
          分配用户
          <i class="el-icon-user"></i>
        </el-button>
        <el-button type="danger" plain @click="groupDelRows" v-show="delGroup">
          批量删除
          <i class="el-icon-delete"></i>
        </el-button>
			</el-row>
      <el-table
        :data="allocationGroupData"
        border
        stripe
        class="clearBeforeLine"
        @selection-change="handleGroupChange"
        style="width: 100%;margin-top:20px;margin-bottom:20px"
        :key="tableKey"
        ref="groupTable"
        >
        <el-table-column type="selection" align="center"></el-table-column>
        <el-table-column min-width="100px" sortable :show-overflow-tooltip="true" prop="userName" label="用户名"></el-table-column>
        <el-table-column min-width="100px" sortable :show-overflow-tooltip="true" prop="name" label="员工姓名"></el-table-column>
        <el-table-column width="70" prop="control" align="center" label="操作">
          <template slot-scope="scope">
            <el-button class="td-btn-icon" type="text" title="删除用户信息" icon="el-icon-delete" @click="handleDelete(scope.$index, allocationGroupData)"></el-button>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="userGroupSaveEvt">
          保存
          <i class="el-icon-document-checked el-icon--right"></i>
        </el-button>
        <el-button type="danger" @click="userGroupCloseEvt">
          关闭
          <i class="el-icon-close"></i>
        </el-button>
      </div>
    </el-dialog>
    <!-- 分配用户组 -->
    <el-dialog
      title="分配用户组"
      :visible.sync="dialogGroupVisible"
      :before-close="handleGroupClose"
      class="demo-ruleForm"
      custom-class="el-dialog-flex"
      :close-on-click-modal="false"
      :close-on-press-escape="false">
      <el-row>
        <el-col :span="15">
          <el-input clearable v-model="textSearchUser" placeholder="请输入用户名/别名" style="width:280px;" @keyup.enter.native="distributionGroupEvent" @clear="distributionGroupEvent">
            <el-button slot="append" icon="el-icon-search" @click="distributionGroupEvent"></el-button>
          </el-input>
        </el-col>
      </el-row>
      <el-table
          :data="grouptableData"
          border
          stripe
          @selection-change="handleSelectionChange"
          style="width: 100%;margin-top:10px;margin-bottom:10px"
          ref="groupTable"
          height="100%"
          >
          <el-table-column type="selection" align="center"></el-table-column>
          <el-table-column min-width="100px" sortable :show-overflow-tooltip="true" prop="userName" label="用户名称"></el-table-column>
          <el-table-column min-width="100px" sortable :show-overflow-tooltip="true" prop="name" label="员工姓名"></el-table-column>
        </el-table>
        <!-- 分页 -->
				<el-pagination
					background
					@size-change="handleSizeUserChange"
					:current-page="currentUserPage"
					@current-change="handleCurrentUserChange"
					:page-size="pageUserSize"
					layout="total, sizes, prev, pager, next, jumper"
					:total="totalUser"
        ></el-pagination>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleGroupSure">
          确定
          <i class="el-icon-document-checked el-icon--right"></i>
        </el-button>
        <el-button @click="handleGroupCloseCheck(false)">
          取消
          <i class="el-icon-refresh-left"></i>
        </el-button>
      </span>
    </el-dialog>
  </el-card>
</template>
<script>
  import {
    Dialog,
    Table,
    TableColumn,
    Pagination,
    MessageBox,
    Message,
    Drawer
  } from 'element-ui';
  import UserDialog from '../../../components/userDialog';
  import { getDomainAuth, userGroupsList, userGroupsDelete, userGroupsAddOrEdit, userList, userGroupAuthId, userGroupAuth, userGroupDataAuth } from '@/api/authority/userGroupManage/userGroupManage.js'
  export default {
    components: {
      'el-dialog': Dialog, // 对话框
      'el-table': Table, // 表格
      'el-table-column': TableColumn, // 表格列
      'el-pagination': Pagination, // 分页
      'el-drawer': Drawer // 对话框
    },
    data() {
      let userGroupVal = {
        userGroupCode: '',
        userGroupName: '',
        domainName: '',
        domainId: '',
        groupStatus: true
      }
      let userGroupSearchVal = {
        groupName: '',
        groupCode: '',
        domainName: '',
        groupStatus: ''
      }
      return {
        readonly: '', // 用户组编码是否禁用
				optionDatas: [],
        formSearch: {}, // 查询参数
        userGroupSearchVal: JSON.parse(JSON.stringify(userGroupSearchVal)),
        userGroupSearchForm: JSON.parse(JSON.stringify(userGroupSearchVal)), // //角色高级查询条件
        userGroupVal: JSON.parse(JSON.stringify(userGroupVal)), // 新增/编辑弹框里的model,用于重置表单
        // 用户组表单项
        userGroupForm: JSON.parse(JSON.stringify(userGroupVal)),
        //表格数据源
        userGroupDatas: [],
        selectedRows: [], //选中的表格数据
        title: '', // 用户组新增/编辑弹窗标题
        userGroupDialogVisible: false, //用户组编辑弹窗
        searchDialogVisible: false, //高级查询弹窗
        authorizationData: [], // 分配用户组
        tableKey: 1, // 自动刷新表格
        dialogGroupVisible: false, // 分配用户组弹框是否展示
        allocationGroupData: [], // 所有分配用户组数据
        checkDatas: [], // 分配用户组选中行数据
        checkGroupDatas: [], // 查询分配用户组选中行数据
        userGroupId: '', // 用户组授权ID
        grouptableData: [],
        expression: '', // 搜索model值
        searchData: [], // 存储搜索来的数据
        total: 0, // 总页数
        pageSize: 20, //每页展示条数
        currentPage: 1, //默认显示页数
        groupId: '', // 得到用户组id
        totalUser: 0, // 分配用户组用户表格总条数
        currentUserPage: 1, // 分配用户组当前页
        pageUserSize: 20, //  分配用户组显示页数
        textSearchUser: '' // 搜索分配用户组的用户
      };
    },
    computed: {
      delGroup () {
        if (this.checkDatas && this.checkDatas.length) return true
        else return false
      },
      groupDelete() {
        if (this.checkGroupDatas && this.checkGroupDatas.length) return true
        else return false
      }
    },
    created() {
      this.userGroupList()
      this.distributionGroupEvent()
      window.onresize = () => {
        this.$refs.groupTable.doLayout() //监听窗口变化，重绘表格布局
      }
      // 获取系统下拉框数据
      getDomainAuth().then(res => {
        this.optionDatas = res.data.data
        // console.log(this.optionDatas)
      })
    },
    methods: {
      /* 过滤无效数据*/
      filterInvalid (dataSource) {
        let validData = {}
        let jsonData = JSON.stringify(dataSource)
        for (let k in dataSource) {
          let data = dataSource[k]
          if (data != "" && data != null && data != undefined && jsonData != "{}" && jsonData != "[]") {
            validData[k] = data
          }
        }
        return validData
      },
      // 获取用户组表格数据事件
      userGroupList() {
        let paramsDatas = {
          page: this.currentPage,
          size: this.pageSize
        }
        if (this.searchDialogVisible) { // 高级查询
          paramsDatas.type = 2
          Object.assign(paramsDatas, this.userGroupSearchForm)
          this.searchDialogVisible = false
        } else { // 模糊查询
          paramsDatas.type = 1
          let expression = this.formSearch.expression
          if (!expression) expression = ""
          paramsDatas.groupName = expression
          paramsDatas.groupCode = expression
        }
        paramsDatas = this.filterInvalid(paramsDatas) //过滤无效数据
        userGroupsList({
          params: paramsDatas
        }).then(res => {
          console.log(res.data.data.records)
          this.total = res.data.data.total
          this.userGroupDatas = res.data.data.records
          setTimeout(() => {
            this.$refs.groupTable.doLayout() //重绘表格宽度，解决表头对不齐的问题
          }, 0)
        })
      },
      // 改变当前页条数
      handleSizeChange (val) {
        this.pageSize = val
        this.userGroupList() //刷新表格
      },
      // 切换页数
      handleCurrentChange (val) {
        this.currentPage = val
        this.userGroupList() //刷新表格
      },
      // 点击复选框
      checkedRow(val) {
        this.selectedRows = val
      },
      // 删除数据
      userGroupDelRow(index, row) {
        MessageBox.confirm("您是否确定删除选中内容", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
        .then(() => {
          this.deleteRowData(row)
        })
        .catch(() => {})
      },
      // 删除事件
      deleteRowData (row) {
        let id = row.userGroupId
        userGroupsDelete(id).then(res => {
          if (res.data.code === 10000) {
            Message.success('删除成功')
            this.userGroupList()
          }
        })
      },
      // 批量删除
      userGroupDelRows() {
        MessageBox.confirm('您确定要删除选中的数据吗?').then(() => {
          console.log(this.selectedRows)
          Message.success('删除成功') //成功提示
        });
      },
      /* 开启用户组新增弹窗 */
      addUserGroupDialog() {
        this.title = '用户组信息'
        this.userGroupDialogVisible = true
        this.readonly = false
      },
      /* 开启用户组编辑弹窗 */
      userGroupEditDialog(row) {
        this.title = '用户组信息'
        this.userGroupId = row.userGroupId
        this.userGroupDialogVisible = true
        this.readonly = true
        this.userGroupForm = JSON.parse(JSON.stringify(row))
        this.getUserGroupAuth(row.userGroupId)
      },
      // 添加用户组下分配的用户
      userGroupEvent (userGroupId) {
        let userIds = []
        this.allocationGroupData.forEach(e => {
          userIds.push(e.userAccountId)
        })
        userGroupAuth({
          id: [userGroupId],
          userIds: userIds
        }).then(res => {
          if (res.data.code === 10000){
            Message.success('添加成功') // 成功提示
            this.userGroupDialogCloseEvt()
            this.userGroupList()
          }
        })
      },
      // 查询用户组下分配的用户
      getUserGroupAuth(userGroupId) {
        this.groupId = userGroupId
        userGroupAuthId(userGroupId).then(res => {
          // console.log(res)
          if (res.data.code === 10000){
            this.allocationGroupData = res.data.data
            setTimeout(() => {
              this.$refs.groupTable.doLayout() // 重绘表格宽度
            }, 0)
          }
        })
      },
      // 跳转授权页面
      giveFuncEvt (row) {
        // let dynamicRouting = [{
        //   path: '/',
        //   component: this.pageLayout,
        //   meta: {
        //     title: '权限管理'
        //   },
        //   children: [
        //     {
        //       path: 'userAuthorization',
        //       name: 'userAuthorization',
        //       component: () => import('@/views/authority/userAuthorization/userAuthorization'),
        //       meta: {
        //         title: '用户组授权'
        //       }
        //     }
        //   ],
        // }]
        // this.$router.addRoutes(dynamicRouting)
        // this.$router.push({
        //   name: 'userAuthorization',
        //   params: {
        //     userGroupId: row.userGroupId
        //   }
        // })
        // this.multiRouters是全局提供的自动添加多级路由的方法
        this.$router.addRoutes(this.multiRouters([{
          path: 'userAuthorization',
          name: 'userAuthorization',
          component: () => import('@/views/authority/userAuthorization/userAuthorization'),
          meta: {
            title: '用户组授权'
          }
        }]))
        this.$router.push(this.routerMatch({
          name: 'userAuthorization',
          params: {
            userGroupId: row.userGroupId
          }
        }))
      },
      /* 开启高级查询弹窗 */
      searchDialog() {
        this.searchDialogVisible = true
      },
      /* 用户组弹窗关闭事件，主要用于清空表单和校验 */
      userGroupDialogCloseEvt() {
        this.$refs.userGroupForm.resetFields() // 重置校验
        this.userGroupForm = JSON.parse(JSON.stringify(this.userGroupVal))
        this.userGroupDialogVisible = false
      },
      /* 高级查询关闭事件，主要用于清空表单和校验 */
      searchDialogCloseEvt() {
        this.searchDialogVisible = false
      },
      // 高级查询弹框重置按钮事件
      userGroupReset () {
        this.$refs.userGroupSearchForm.resetFields()
        this.searchDialogVisible = false
        this.userGroupList() //刷新表格
      },
      /* 用户组保存事件 */
      userGroupSaveEvt() {
        this.$refs.userGroupForm.validate(valid => {
          if (!valid) return false
          if (this.userGroupId) {
            let sendDatas = this.filterInvalid({
              userGroupId: this.userGroupId,
              userGroupName: this.userGroupForm.userGroupName,
              userGroupCode: this.userGroupForm.userGroupCode,
              domainId: this.userGroupForm.domainId,
              groupStatus: this.userGroupForm.groupStatus
            })
            userGroupsAddOrEdit(sendDatas).then(res => {
              console.log(res)
              if (res.data.code === 10000) { // 保存接口调用成功
                if (this.allocationGroupData.length > 0) { //  如果分配人员表格有数据,去进行下一个接口
                  let userGroupId = res.data.data
                  this.userGroupEvent(userGroupId)
                } else {
                  this.userGroupCloseEvt() // 如没数据,就直接关闭弹
                  this.userGroupList()
                }
              }
            })
          } else {
            let sendDatas = this.filterInvalid({
              userGroupName: this.userGroupForm.userGroupName,
              userGroupCode: this.userGroupForm.userGroupCode,
              domainId: this.userGroupForm.domainId,
              groupStatus: this.userGroupForm.groupStatus
            })
            userGroupsAddOrEdit(sendDatas).then(res => {
              console.log(res)
              if (res.data.code === 10000) { // 保存接口调用成功
                if (this.allocationGroupData.length > 0) { //  如果分配人员表格有数据,去进行下一个接口
                  let dataId = res.data.data
                  this.userGroupEvent(dataId)
                } else {
                  this.userGroupCloseEvt() // 如没数据,就直接关闭弹框
                  this.userGroupList()
                }
              }
            })
          }
        })
      },
      // 点击新增编辑取消事件
      userGroupCloseEvt() {
        this.userGroupDialogCloseEvt()
      },
      // 点击tabel里的用户组状态触发编辑接口事件
      userGroupStatusclick (index, row) {
        let sendDatas = this.filterInvalid({
          userGroupId: row.userGroupId,
          userGroupName: row.userGroupName,
          userGroupCode: row.userGroupCode,
          groupStatus: row.groupStatus
        })
        userGroupsAddOrEdit(sendDatas).then(res => {
          console.log(res)
          if (res.data.code === 10000) {
            Message.success('操作成功') // 成功提示
            // this.userGroupDialogCloseEvt()
            this.userGroupList()
          }
        })
      },
      // 查询分配用户组击复选框
      handleGroupChange (val) {
        this.checkGroupDatas = val
        console.log(this.checkGroupDatas)
      },
      // 分配用户组击复选框
      handleSelectionChange (val) {
        this.checkDatas = val
        console.log(this.checkDatas)
      },
      // 获取所有分配组数据
      distributionGroupEvent () {
        let data = {
          page: this.currentUserPage,
          size: this.pageUserSize
        }
        data.type = 1
        data.userName = this.textSearchUser
        data.name = this.textSearchUser
        userList({
          params: data
        }).then(res => {
          // console.log(res)
          this.grouptableData = res.data.data.records
          this.totalUser = res.data.data.total
          setTimeout(() => {
            this.$refs.groupTable.doLayout() // 表格刷新以后，重绘表格宽度
          }, 0)
        })
      },
      // 分配用户组
      distributionGroup () {
        this.dialogGroupVisible = true
      },
      // 批量删除
      groupDelRows () {
        console.log('3333')
      },
      // 单行删除
      handleDelete (index, data) {
        MessageBox.confirm('是否确定要删除该行数据?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        .then(() => {
          this.delRowData(index, data)
        })
        .catch(() => {})
      },
      // 删除事件
      delRowData(index, data) {
        let userAccountId = data[index].userAccountId
        if (!userAccountId) {
          data.splice(index, 1)
          return
        }
        userGroupDataAuth({
          id: [this.groupId],
          userIds: [userAccountId]
        }).then(res => {
          console.log(res.data.code)
          if (res.data.code === 10000) {
            Message.success('删除成功')
            data.splice(index, 1)
          }
        })
      },
      // 关闭分配用户组弹框
      handleGroupClose () {
        this.dialogGroupVisible = false
        this.$refs.groupTable.clearSelection()
      },
      // 点击取消分配用户组弹框触发事件
      handleGroupCloseCheck () {
        this.handleGroupClose()
      },
      // 点击确认分配用户组弹框触发事件
      handleGroupSure () {
        // this.allocationGroupData = this.allocationGroupData.concat(this.checkDatas)
        let userIds = []
        this.allocationGroupData.forEach(e => {
          userIds.push(e.userAccountId)
        })
        this.checkDatas.forEach(e => {
          if (userIds.indexOf(e.userAccountId) == -1) {
            e.userAccountId = e.userAccountId
            this.allocationGroupData.push(e)
          }
        })
        this.handleGroupClose()
      },
      // 分配用户组弹框里分页里每页数据
      handleSizeUserChange (val) {
        this.pageUserSize = val
        this.distributionGroupEvent()
      },
      // 分配用户组弹框里分页里当前页数
      handleCurrentUserChange (val) {
        this.currentUserPage = val
        this.distributionGroupEvent()
      }
    }
  };
</script>
<style lang="scss">
  .clearBeforeLine .el-table__fixed-right::before {
    display: none;
  }
  .el-form--inline .el-form-item {
    margin-bottom: 10px;
  }
</style>
